package org.jjche.file.modules.file.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.jjche.common.enums.LogCategoryType;
import org.jjche.common.enums.LogType;
import org.jjche.common.param.MyPage;
import org.jjche.common.param.PageParam;
import org.jjche.common.wrapper.response.R;
import org.jjche.core.base.BaseController;
import org.jjche.file.constant.FileApiVersion;
import org.jjche.file.modules.file.api.FileApi;
import org.jjche.file.modules.file.api.vo.FileVO;
import org.jjche.file.modules.file.dto.FileQueryCriteriaDTO;
import org.jjche.file.modules.file.service.FileService;
import org.jjche.log.biz.starter.annotation.LogRecord;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 文件
 * </p>
 *
 * @author miaoyj
 * @since 2024-07-10
 */
@Api(tags = "存储：文件")
@RestController
@RequestMapping
@RequiredArgsConstructor
public class FileController extends BaseController {

    private final FileService fileService;
    private final FileApi fileApi;

    @ApiOperation("查询文件")
    @GetMapping
    @PreAuthorize("@el.check('file:list')")
    public R<MyPage<FileVO>> query(FileQueryCriteriaDTO criteria, PageParam pageable) {
        return R.ok(fileService.pageQuery(criteria, pageable));
    }

    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('file:list')")
    public void download(HttpServletResponse response, FileQueryCriteriaDTO criteria) throws IOException {
        fileService.download(fileService.queryAll(criteria), response);
    }

    @ApiOperation("上传文件")
    @PostMapping("upload")
    public R<FileVO> upload(@RequestPart("file") MultipartFile file) {
        return R.ok(fileApi.upload(file));
    }

    @ApiOperation("上传图片")
    @PostMapping("upload-image")
    public R<FileVO> uploadImage(@RequestPart("file") MultipartFile file) {
        return R.ok(fileApi.uploadImage(file));
    }

    @LogRecord(
            value = "多选删除", category = LogCategoryType.MANAGER,
            type = LogType.DELETE, module = FileApiVersion.MODULE_FILE
    )
    @DeleteMapping
    @ApiOperation("多选删除")
    @Transactional(rollbackFor = Exception.class)
    public R delete(@RequestBody List<String> ids) {
        fileApi.delete(ids);
        return R.ok();
    }
}
